import {
  LOADING,
  HIDE_LOADING,
  SET_TABLE_LIST,
  ADD_TABLE_ITEM,
  EDIT_TABLE_ITEM,
  EDL_TABLE_ITEM,
  CHANGE_PAGE
} from './constants';
import { insertItem, editItemById, delItemByIdArray } from '@/utils/list';

export const UnitReducer = (state, action) => {
  switch (action.type) {
    case LOADING:
      return { ...state, loading: true };
    case HIDE_LOADING:
      return { ...state, loading: false };
    case SET_TABLE_LIST:
      return {
        ...state,
        total: action.data.totalCount,
        tableList: action.data.results,
        loading: false
      };
    case ADD_TABLE_ITEM:
      return {
        ...state,
        tableList: insertItem(action.data, state.tableList)
      };
    case EDIT_TABLE_ITEM:
      return {
        ...state,
        tableList: editItemById(action.id, action.data, state.tableList)
      };
    case EDL_TABLE_ITEM:
      return {
        ...state,
        tableList: delItemByIdArray(action.ids, state.tableList)
      };
    case CHANGE_PAGE: {
      const listQuery = { ...state.listQuery };
      action.info.forEach(({ key, value }) => {
        listQuery[key] = value;
      });
      return {
        ...state,
        listQuery
      };
    }
    default:
      console.log('reducer default');
      return state;
  }
};
